package com.movitech.mobile.cz.base.supplier.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.DateUtils;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.common.utils.IdGen;
import com.movitech.mobile.cz.base.supplier.entity.SMyDeals;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSMyDeals;
import com.movitech.mobile.cz.base.supplier.mapper.SMyDealsMapper;
import com.movitech.mobile.cz.base.supplier.mapper.ext.ExtSMyDealsMapper;
import com.movitech.mobile.cz.base.supplier.service.SMyDealsService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 我的待办已办 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-03-06
 */
@Service("sMyDealsService")
@Transactional
public class SMyDealsServiceImpl extends ServiceImpl<SMyDealsMapper, SMyDeals> implements SMyDealsService {

	private static Logger logger = Logger.getLogger(SMyDealsServiceImpl.class);
	
    @Autowired
    private SMyDealsMapper sMyDealsMapper;
    @Autowired
    private ExtSMyDealsMapper extSMyDealsMapper;

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = { "RuntimeException", "Exception" })
    @Override
    public boolean saveSMyDeals(SMyDeals sMyDeals) {
        sMyDeals.setId(IdGen.uuid());
        sMyDeals.setDoneFlag(CommonConstants.NO_INTEGER);
        
        Date createDate = new Date();
        String userId = UserUtils.getCurrentUserId();
        
        sMyDeals.setCreateBy(userId);
        sMyDeals.setCreateDate(createDate);
        sMyDeals.setUpdateBy(userId);
        sMyDeals.setUpdateDate(createDate);
        sMyDeals.setDelFlag(CommonConstants.NO_INTEGER);
        int i = sMyDealsMapper.insert(sMyDeals);
        return i > 0;
    }

	@Override
	public boolean updateSMyDealsById(SMyDeals sMyDeals) {
		
		Date updateDate = new Date();
        String userId = UserUtils.getCurrentUserId();
        
        sMyDeals.setDealDoneTime(updateDate);
        sMyDeals.setUpdateBy(userId);
        sMyDeals.setUpdateDate(updateDate);
        sMyDeals.setDelFlag(CommonConstants.NO_INTEGER);
        
        int i = sMyDealsMapper.updateById(sMyDeals);
		
		return i > 0;
	}

	@Override
	public boolean dealMyDeals(String relatedId, String subRelatedId, int dealActionType) {
		SMyDeals sMyDealsParam = new SMyDeals();
		sMyDealsParam.setRelatedId(relatedId);
		sMyDealsParam.setSubRelatedId(relatedId);
		sMyDealsParam.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
		sMyDealsParam.setActionType(dealActionType);

		SMyDeals update = new SMyDeals();
		update.setDoneFlag(CommonConstants.YES_INTEGER);
		update.setDealDoneTime(new Date());
		update.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);
		return update(update,new EntityWrapper<>(sMyDealsParam));
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = { "RuntimeException", "Exception" })
	@Override
	public boolean dealMyDeals(String relatedId, String subRelatedId, int dealType, String[] userIds, 
			int subDealType, int dealActionType, String dealTile, String userId, boolean batchUpdate, String thridRelatedId) {
		
		try{
			boolean updateOldFlag = false;
			boolean saveNewFlag = false;
			
			//1.更新已办
			SMyDeals sMyDealsParam = new SMyDeals();
			sMyDealsParam.setDealType(dealType);
			sMyDealsParam.setRelatedId(relatedId);
			if(StringUtils.isNotBlank(thridRelatedId)){
				sMyDealsParam.setThirdRelatedId(thridRelatedId);
			}
			if(!batchUpdate){
				sMyDealsParam.setUserId(userId);
				sMyDealsParam.setSubRelatedId(subRelatedId);
			}
			
			sMyDealsParam.setDoneFlag(CommonConstants.NO_INTEGER);
			
			EntityWrapper wrapper = new EntityWrapper<>();
			wrapper.setEntity(sMyDealsParam);
			List<SMyDeals> updateDoneMyDealList = sMyDealsMapper.selectList(wrapper);
			if(updateDoneMyDealList != null && updateDoneMyDealList.size() > 0){
				for(SMyDeals updateDoneMyDeal : updateDoneMyDealList){
					updateDoneMyDeal.setDoneFlag(CommonConstants.YES_INTEGER);
					updateDoneMyDeal.setDealDoneTime(new Date());
					updateDoneMyDeal.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
				}
				updateOldFlag = this.updateBatchById(updateDoneMyDealList);
			}
			
			
			//2.添加待办
			if(userIds != null && userIds.length > 0){
				SMyDeals sMyDeals = new SMyDeals();
				
				for(String uId :  userIds){
					sMyDeals.setUserId(uId);
					sMyDeals.setDealType(dealType);
					sMyDeals.setDealSubType(subDealType);
					sMyDeals.setRelatedId(relatedId);
					sMyDeals.setSubRelatedId(subRelatedId);
					if(StringUtils.isNotBlank(thridRelatedId)){
						sMyDeals.setThirdRelatedId(thridRelatedId);
					}
					sMyDeals.setDealTitle(dealTile);
					sMyDeals.setActionType(dealActionType);
					
					saveNewFlag = this.saveSMyDeals(sMyDeals);
				}
				
			}else{//不需要走待办
				saveNewFlag = true;
			}
			
			
			return true;
			
		} catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------dealMyDeals-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
		
	}


	@Override
	public List<SMyDeals> getMyDealsListByUserAndStatus(Map<String, Object> map) {
		return extSMyDealsMapper.getMyDealsListByUserAndStatus(map);
	}

	@Override
	public List<SMyDeals> getOuterDealsList(Map<String, Object> map) {
		return extSMyDealsMapper.getOuterDealsList(map);
	}

	@Override
	public boolean deleteSmyDealsById(String id) {
		Date now = DateUtils.getNow();
		String currentUserId = UserUtils.getCurrentUserId();
		SMyDeals sd = new SMyDeals();
		sd.setId(id);
		sd.setDoneFlag(CommonConstants.DEL_FLAG_DELETE);
		sd.setDealDoneTime(now);
		sd.setUpdateBy(currentUserId);
		sd.setUpdateDate(now);
		return updateById(sd);
	}

	@Override
	public boolean deleteNoDonedByFormId(String relateId) {
		SMyDeals sd = new SMyDeals();
		sd.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
		EntityWrapper entityWrapper = new EntityWrapper();
		SMyDeals where = new SMyDeals();
		where.setRelatedId(relateId);
		where.setDoneFlag(CommonConstants.NO_INTEGER);
		entityWrapper.setEntity(where);

		return update(sd,entityWrapper);
	}

	@Override
	public boolean updateDeleteStatusByRelateIdAndTaskId(String relateId, String taskId,Integer deleteFlag) {
		SMyDeals sd = new SMyDeals();
		sd.setDelFlag(deleteFlag);
		return update(sd,new EntityWrapper<SMyDeals>().eq("related_id",relateId).eq("flow_task_id",taskId));
	}

	@Override
	public boolean deleteByEntityExceptUsers(SMyDeals sMyDeals, List<String> exceptUserIds) {
		Date now = DateUtils.getNow();
		EntityWrapper entityWrapper = new EntityWrapper();
		entityWrapper.setEntity(sMyDeals);
		if(CollectionUtils.isNotEmpty(exceptUserIds))
			entityWrapper.notIn("user_id",exceptUserIds);

		SMyDeals sd = new SMyDeals();
		sd.setUpdateBy(UserUtils.getCurrentUserId());
		sd.setUpdateDate(now);
		sd.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
		return update(sd,entityWrapper);
	}

	@Override
	public boolean deleteBatchByEntityAndUsers(SMyDeals sMyDeals, List<String> userids) {
		Date now = DateUtils.getNow();
		EntityWrapper entityWrapper = new EntityWrapper();
		entityWrapper.setEntity(sMyDeals);
		if(CollectionUtils.isNotEmpty(userids)){
			entityWrapper.in("user_id",userids);
			sMyDeals.setUserId(null);
		}
		SMyDeals sd = new SMyDeals();
		sd.setUpdateBy(UserUtils.getCurrentUserId());
		sd.setUpdateDate(now);
		sd.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
		return update(sd,entityWrapper);
	}

	@Override
	public boolean doneById(String id) {
    	SMyDeals sMyDeals = new SMyDeals();
    	sMyDeals.setDoneFlag(CommonConstants.DEL_FLAG_DELETE);
		sMyDeals.setDealDoneTime(DateUtils.getNow());
    	sMyDeals.setId(id);
		return updateById(sMyDeals);
	}

	@Override
	public boolean doneByEntityAndUsers(SMyDeals sMyDeals, List<String> userids,String remark) {
		Date now = DateUtils.getNow();
		EntityWrapper entityWrapper = new EntityWrapper();
		entityWrapper.setEntity(sMyDeals);
		entityWrapper.notIn("done_flag",CommonConstants.YES_INTEGER);
		if(CollectionUtils.isNotEmpty(userids)){
			entityWrapper.in("user_id",userids);
			sMyDeals.setUserId(null);
		}
		SMyDeals sd = new SMyDeals();
		sd.setUpdateBy(UserUtils.getCurrentUserId());
		sd.setUpdateDate(now);
		sd.setDoneFlag(CommonConstants.YES_INTEGER);
		sd.setDealDoneTime(now);
		sd.setRemarks(remark);
		return update(sd,entityWrapper);
	}

	@Override
	public SMyDeals selectUntreatedById(String id) {
    	EntityWrapper entityWrapper = new EntityWrapper();
    	SMyDeals sMyDeals = new SMyDeals();
    	sMyDeals.setId(id);
    	sMyDeals.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
    	sMyDeals.setDoneFlag(CommonConstants.UNDONG_FLAG);
		entityWrapper.setEntity(sMyDeals);
		return selectOne(entityWrapper);
	}

	@Override
	public SMyDeals selectById(String id) {
		EntityWrapper entityWrapper = new EntityWrapper();
		SMyDeals sMyDeals = new SMyDeals();
		sMyDeals.setId(id);
		sMyDeals.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
		entityWrapper.setEntity(sMyDeals);
		return selectOne(entityWrapper);
	}

	@Override
	public SMyDeals selectOneByEntity(SMyDeals sMyDeals) {
		EntityWrapper entityWrapper = new EntityWrapper();
		entityWrapper.setEntity(sMyDeals);
		sMyDeals.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
		sMyDeals.setUserId(UserUtils.getCurrentUserId());
		entityWrapper.orderBy("create_date",false);
		return selectOne(entityWrapper);
	}

	@Override
	public int getToDoOrDoneListCounts(String userId, int dealType, List<Integer> dealSubTypeList, boolean includeFlag, int doneFlag) {
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userId", userId);
		param.put("dealType", dealType);
		param.put("dealSubTypeList", dealSubTypeList);
		param.put("includeFlag", includeFlag);
		param.put("doneFlag", doneFlag);
		
		return extSMyDealsMapper.getToDoOrDoneListCounts(param);
	}

	@Override
	public long getMyDealListByParamsCounts(Map<String, Object> map) {
		return extSMyDealsMapper.getMyDealListByParamsCounts(map);
	}

	@Override
	public List<ExtSMyDeals> getMyDealListByParams(Map<String, Object> map) {
		return extSMyDealsMapper.getMyDealListByParams(map);
	}

	@Override
	public int updateSMyDealsByEntity(SMyDeals sMyDeals) {
//		SMyDeals sMyDealsDB = baseMapper.selectOne(sMyDeals);
//		sMyDealsDB.setDoneFlag(CommonConstants.DONG_FLAG);
//		sMyDealsDB.setDealDoneTime(new Date());
//		sMyDealsDB.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);
		EntityWrapper entityWrapper = new EntityWrapper();
		entityWrapper.setEntity(sMyDeals);

		SMyDeals sMyDealsUpdate = new SMyDeals();
		sMyDealsUpdate.setDoneFlag(CommonConstants.DONG_FLAG);
		sMyDealsUpdate.setDealDoneTime(new Date());
		sMyDealsUpdate.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);
		return baseMapper.update(sMyDealsUpdate,entityWrapper);
	}

	@Override
	public void updateUserByEntity(String userId, SMyDeals sMyDealsWhere) {
		EntityWrapper entityWrapper = new EntityWrapper();
		entityWrapper.setEntity(sMyDealsWhere);
		SMyDeals update = new SMyDeals();
		update.setUserId(userId);
		update(update,entityWrapper);
	}

	@Override
	public boolean isDone(String dealId) {
		SMyDeals where = new SMyDeals();
		where.setId(dealId);
		where.setDoneFlag(CommonConstants.UNDONG_FLAG);
		where.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
		return selectCount(new EntityWrapper<>(where))<=0;
	}

	@Override
	public boolean isDone(String userId, String rcId, String subRcId, Integer actionType) {
		SMyDeals where = new SMyDeals();
		where.setUserId(userId);
		where.setRelatedId(rcId);
		where.setSubRelatedId(subRcId);
		where.setActionType( actionType);
		where.setDoneFlag(CommonConstants.UNDONG_FLAG);
		where.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);

		return selectCount(new EntityWrapper<>(where))<=0;
	}

}
